var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    "value": "",   // 文本的内容
    "placeholder": "请输入文本",
    "maxlength": 100,  // 最大输入长度，设置为 -1 的时候不限制最大长度
    "focus": true,
    "auto-height": true,  // 是否自动增高，设置auto-height时，style.height不生效
    "adjust-position": true, // 键盘弹起时，是否自动上推页面
   title:[],
   coupon:0,
    username:'',
    telephone:'',
    wholeAddress:'',
    reducePrice:0,
    ucId:0,
    freight:0,
    remark:"",
    choo_modal:"none",
    checked:true,
    radioValue:1,
    onFocus: true,    //textarea焦点是否选中
    isShowText:true, //控制显示 textarea 还是 text
    remark: '',
    index:-1,
    img:1,
  },
  //选择地址
  bindaddress: function () {
    wx.navigateTo({
      url: '/pages/addressList/addressList?userId='+wx.getStorageSync("userId")
      })
  },
  
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
  //  var type = options.type;
    //获取手机高度
    this.setData({
      navH: app.globalData.navHeight
    })
    that.setData({
      taskId: options.taskId,
      questionId: options.questionId,
      type: options.type,
      pAndNList: options.pAndNList,
      addrId:options.addrId,
      index:options.index,
      typeShow: options.typeShow,
      groupShoppingId: options.groupShoppingId,
    })
    console.info("这是邀请" + that.data.groupShoppingId);
    that.setData({
      pAnd: JSON.parse(that.data.pAndNList)
    })
    var pAnd1 = that.data.pAnd;
    console.info(pAnd1);
    var priceCount = 0;
    var point = 0;
    var productId=0;
    for (var i = 0; i < pAnd1.length; ++i) {
      priceCount += pAnd1[i].num * pAnd1[i].price;
      point += pAnd1[i].num * pAnd1[i].point;
      productId = pAnd1[i].productId
    }
    that.setData({
      price: parseFloat(priceCount.toFixed(2)),
      price1: parseFloat(priceCount.toFixed(2)),
      price3: parseFloat(priceCount.toFixed(2)),
      point: point,
      productId: productId
    })
    wx.loadFontFace({
      family: 'fonts',
      source: 'url("https://test.jwsxmall.com/jiweishengxian/VisbyCF-Bold.otf")',
      success(res) {
        console.log(res.status)
        that.setData({ loaded: true })
      },
      fail: function (res) {
        console.log(res.status)
      },
      complete: function (res) {
        console.log(res.status)
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    var that = this;
    that.setData({
      balance: wx.getStorageSync("balance")
    })
    const pages = getCurrentPages()
    const currPage = pages[pages.length - 1]  // 当前页
    console.info(that.data.typedianji);
    if (that.data.typedianji==1) {
      that.setData({
        price1: parseFloat((that.data.price - that.data.reducePrice).toFixed(2)) < 0 ? 0.01 : parseFloat((that.data.price - that.data.reducePrice).toFixed(2))
      })
    } else {
      that.setData({
        price1: parseFloat(that.data.price.toFixed(2))
      })
    }
    
    
   
    if (wx.getStorageSync("points") == 0) {
      that.setData({
        points: 0
      })
    } else {
      that.setData({
        points: wx.getStorageSync("points")
      })
    }
    wx.request({
      url: app.globalData.url + "getUserAddressList",
      method: "GET",
      data: {
        userId: wx.getStorageSync("userId")
      },
      success: function (res) {
        var data = res.data.data;
        if (res.data.result == 1) {
         
          if (data.length > 0) {
            if (currPage.data.wholeAddress == ""&&that.data.index==-1) {
              that.setData({
                data: data.length,
                username: data[0].username,
                telephone: data[0].telephone,
                provinceName: data[0].provinceName,
                cityName: data[0].cityName,
                districtName: data[0].districtName,
                streetName: data[0].streetName,
                wholeAddress: data[0].wholeAddress,
                addrid: data[0].addrId,

              })
              console.info("adad" + that.data.addrid);
              that.addJson(that.data.addrid);
            } else if (that.data.index != -1){
                console.info(data);
                that.setData({
                data: data.length,
                username: data[that.data.index].username,
                telephone: data[that.data.index].telephone,
                provinceName: data[that.data.index].provinceName,
                cityName: data[that.data.index].cityName,
                districtName: data[that.data.index].districtName,
                streetName: data[that.data.index].streetName,
                wholeAddress: data[that.data.index].wholeAddress,
                addrid: data[that.data.index].addrId,
              })
              console.info("adad===" + currPage.data.addrid);
              that.addJson(that.data.addrId);
            }else {

              console.info("adad===" + currPage.data.addrid);
              that.addJson(that.data.addrId);
            }
            
          } else {
            that.setData({
              data: 0
            })
            that.addJson(that.data.addrId);
          }

        }
      }
    });
    var str = "";
    var str1 = "";
    var str2 = "";
    for(var i=0;i<that.data.pAnd.length;i++){
      str += that.data.pAnd[i].productId+",";
      str1 += that.data.pAnd[i].num + ",";
      str2 += that.data.pAnd[i].price + ",";
    }
    str = str.substring(0,str.length-1);
    str1 = str1.substring(0, str1.length - 1);
    str2 = str2.substring(0, str2.length - 1);
    wx.request({
      url: app.globalData.url + 'getUserConponListByUserId',
      method: 'GET',
      data: {
        userId: wx.getStorageSync("userId"),
        type: 1,
        threshold: that.data.price,
        productIdList: str,
        productNumList: str1,
        productPriceList: str2
      },
      success: function (res) {
        that.setData({
          couponsList: res.data.data
        });
      },
    });
    
  },

  addtion: function(e){
    var that = this;
    var index = e.currentTarget.dataset.index; // 获取data- 传进来的index
    var arr = that.data.pAnd;
    console.info(that.data.pAnd);  
    if (arr[index].seckillNum > 0){
      if (arr[index].num < arr[index].seckillNum) {
        arr[index].num++;
      }else{
        wx.showToast({
          title: '达到限购数量',
          icon: "none"
        })
      }
    } else {
      arr[index].num++;
    }
      that.setData({
        pAnd: arr
      });
      var priceCount = 0;
      var point = 0;
      for (var i = 0; i < arr.length; ++i) {
        priceCount += arr[i].num * arr[i].price;
        point += arr[i].num * arr[i].point;
      }
      that.setData({
        price: parseFloat(priceCount.toFixed(2)),
        price1: parseFloat(priceCount.toFixed(2)),
        price3: parseFloat(priceCount.toFixed(2)),
        point: point
      })
    
  },

  subtraction: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index; // 获取data- 传进来的index
    var arr = that.data.pAnd;
    if (arr[index].num > 1){
      arr[index].num--;
      that.setData({
        pAnd: arr
      });
      var priceCount = 0;
      var point = 0;
      for (var i = 0; i < arr.length; ++i) {
        priceCount += arr[i].num * arr[i].price;
        point += arr[i].num * arr[i].point;
      }
      that.setData({
        price: parseFloat(priceCount.toFixed(2)),
        price1: parseFloat(priceCount.toFixed(2)),
        price3: parseFloat(priceCount.toFixed(2)),
        point: point
      })
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  addJson: function (addrid) {
    var that = this;
    var productId = "";
    for (var i = 0; i < that.data.pAnd.length; i++) {
      productId += '{"productId":' + that.data.pAnd[i].productId + ',"num":' + that.data.pAnd[i].num + '},';
    }
    productId = productId.substr(0, productId.length - 1);
    var addrid = that.data.addrid
    if (addrid==undefined) {
      addrid=0;
    }
    var json = '{"addressId" :' + addrid + ',"product":[' + productId+']}';
    console.info(json);
    wx.request({
      url: app.globalData.url + "getTotalFreight",
      method: "GET",
      data: {
        json: JSON.parse(json)
      },
      success: function (res) {
        var data = res.data.data;
        if (res.data.result == 1) {
          // that.setData({
          //   freight:0
          // })
           freight: parseFloat(data.toFixed(2));
            if (that.data.reducePrice==0) {
              // price1: (that.data.price1 - data).toFixed(2)
              that.setData({
                freight: parseFloat(data.toFixed(2)),
                price1: parseFloat((that.data.price1 - data).toFixed(2))
              })
          }
          
        }
      }
    });
  },
  bindSubmitOrder:function(){
    var that = this;
    
    var userId = wx.getStorageSync("userId");
    var points = wx.getStorageSync("points");
    if (that.data.taskId == undefined) {
      that.setData({
        taskId:0
      })
    }
    if (that.data.questionId == undefined) {
      that.setData({
        questionId: 0
      })
    }
    if (that.data.addrid == undefined) {
      wx.showToast({
        title: "请添加收货地址",
        icon: 'none'
      })
      return;
    }
    if (that.data.groupShoppingId==undefined) {
      that.setData({
        groupShoppingId:0
      })
    }
    if (that.data.pAndNList!=undefined) {
        var type = that.data.type;
        console.info(type);
        if(type == undefined) {
          type = 1;
        }
        if (that.data.radioValue == 2)  {
          var banlance = true;
        } else {
          var banlance = false;
        }
        console.info(that.data.ucId);
        wx.showLoading({
          title: '正在提交...',
          icon: 'loading',
        })
        wx.request({
          url: app.globalData.url + "submitOrder",
          method: "GET",
          data: {
            userId: userId,
            taskId: that.data.taskId,
            questionId: that.data.questionId,
            productIdAndNumList: that.data.pAnd,
            addressId: that.data.addrid,
            type: type,
            couponId: that.data.ucId,
            remark: that.data.remark,
            banlance: banlance,
            groupShoppingId: that.data.groupShoppingId,
            payChannel: 5003
          },
          success: function (res) {
            var data = res.data.data;
            console.log(res.data);
            that.setData({
              orderid: data.orderId,
            })
            if (res.data.result != 1){
              wx.showToast({
                title: res.data.errmsg,
                icon: 'none'
              })
              return;
            }
            if ( data.orderStatus != 7001) {
              // that.modal_s();
              that.setData({
                userId: userId,
                orderId: data.orderId,
              })
                wx.request({
                  url: app.globalData.url + 'getOrderWeixinPrepayId',
                  data: {
                    userId: userId,
                    orderId: data.orderId,
                    orderNumber: data.orderNumber,
                  },
                  method: "POST",
                  header: {
                    'content-type': 'application/x-www-form-urlencoded'
                  },
                  success: function (res) {
                    var resultData = res.data;
                    var hisId = resultData.hisId;
                    if (res.data.result != 1 && res.data.result != 9) {
                      wx.showToast({
                        title: "数据异常，请稍后重试",
                        icon: 'none'
                      })
                      return;
                    }
                    wx.requestPayment({
                      'timeStamp': resultData.timeStamp,
                      'nonceStr': resultData.nonceString,
                      'package': resultData.packageStr,
                      'signType': resultData.signType,
                      'paySign': resultData.sign,
                      //支付成功
                      success: function (res) {
                        if ("requestPayment:ok" === res.errMsg) {
                          wx.showToast({
                            title: '支付成功',
                            icon: 'success',
                            duration: 2000,
                            success: function () {
                              if (that.data.type==2){
                                console.info(that.data.orderid);
                                wx.navigateTo({
                                  url: '/pages/assembleDetail/assembleDetail?orderId=' + that.data.orderid+'&back=1'
                                })
                              } else {
                                setTimeout(function () {
                                  wx.navigateBack({
                                    delta: 2,
                                  });
                                }, 2000) //延迟时间
                              }
                              
                            }
                          })
                        }
                      },
                      //支付或者取消失败
                      fail: function (res) {
                        if ("requestPayment:fail cancel" === res.errMsg) {
                          wx.showToast({
                            title: '取消支付',
                            icon: 'none',
                            duration: 2000,
                            success: function () {
                              if (that.data.type == 2) {
                                wx.navigateBack({
                                });
                                wx.request({
                                  url: app.globalData.url + 'delOrder',
                                  method: 'GET',
                                  data: {
                                    orderId: that.data.orderid,
                                    userId: wx.getStorageSync("userId")
                                  },
                                  success: function (res) {
                                    wx.navigateBack({ // 返回首页
                                      delta: 1,
                                    })
                                  }
                                });
                              } else {
                                setTimeout(function () {
                                  wx.navigateBack({
                                    delta: 1,
                                  });
                                }, 2000) //延迟时间
                              }
                              
                            }
                          })
                          wx.navigateBack({
                            delta: 2,
                          });
                        } else {
                          wx.showToast({
                            title: "支付失败",
                            icon: 'none'
                          })
                        }
                      },
                    })
                  }
                })
            } else if(res.data.result == 1 && res.data.data.orderStatus == 7001){
              wx.showToast({
                title: '支付成功',
                icon: 'success',
                duration: 2000,
                success: function () {
                  console.log('haha');
                  setTimeout(function () {
                    wx.navigateBack({
                      delta: 2,
                    });
                  }, 2000) //延迟时间
                }
              })
            }
          }
        });
    }
  },
  youhui:function(){
    var that = this;
    console.info(that.data.price);
    wx.navigateTo({
      url: '/pages/chooseCoupons/chooseCoupons?price=' + that.data.price + "&productList=" +JSON.stringify(that.data.pAnd)
    })
  },
  onShowTextare() {       //显示textare
    this.setData({
      isShowText: false,
      onFacus: true
    })
  },
  onShowText() {       //显示text
    this.setData({
      isShowText: true,
      onFacus: true
    })
  },
  onRemarkInput(event) {               //保存输入框填写内容
    var value = event.detail.value;
    this.setData({
      remark: value,
    });
  },
  // 弹出
  trueMail: function (e) {
    this.setData({
      choo_modal: "block",
      //z:true
    });
  },
  //消失
  modal_n: function () {
    this.setData({
      choo_modal: "none",
      //z:false
    });
  },
  chooseThis: function (e) {
    this.setData({
      img: e.currentTarget.dataset.index,
    });
  },
  radio: function (e) {
    var that = this;
    var radioValue = e.currentTarget.dataset.value;
    that.setData({
      radioValue: radioValue
    })
    console.info(radioValue);
    if (radioValue == 1) {
      that.setData({
        checked1:false,
        checked:true
      })
    }
    if (radioValue == 2) {
      that.setData({
        checked1: true,
        checked: false
      })
    }
  },
  navBack: function () {
    wx.navigateBack({
      data:1
    })
  }
})